package com.visionork.android.twe.activity;

import java.util.ArrayList;
import java.util.List;

import com.visionork.android.twe.parser.EpisodeAdapterImpl;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class EpisodeActivity extends ListActivity {
	public static final String EPISODE_TITLE = "EPISODE_TITLE";
	public static final String EPISODE_URL = "EPISODE_URL";
	private String _episode_url;
	private String _episode_title;
	private ArrayList<Episode> _episode_list;
	private ProgressDialog _pd;

	private class LoadEpisodoeTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			_episode_list = (new EpisodeAdapterImpl(_episode_url))
					.get_episode_list();
			return null;
		}

		@Override
		protected void onPreExecute() {
			_pd = ProgressDialog.show(EpisodeActivity.this, "加载中...", "读取视频列表", true, false);
		}
		@Override
		protected void onPostExecute(Void param) {
			List<String> titles = new ArrayList<String>(get_episode_list()
					.size());

			for (Episode episode : get_episode_list()) {
				titles.add(episode.get_title());
			}
			setListAdapter(new ArrayAdapter<String>(EpisodeActivity.this,
					R.layout.episode_list_item, titles));
			_pd.dismiss();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.episode_list);
		_episode_url = getIntent().getStringExtra(EPISODE_URL);
		_episode_title = getIntent().getStringExtra(EPISODE_TITLE);
		TextView tv = (TextView) findViewById(R.id.episode_title);
		tv.setText(_episode_title);
		load_episode();
	}

	private void load_episode() {
		LoadEpisodoeTask task = new LoadEpisodoeTask();
		task.execute(new Void[] {});
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Episode episode = get_episode_list().get(position);
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
				+ episode.get_id()));
		startActivity(intent);
	}

	protected ArrayList<Episode> get_episode_list() {
		if (_episode_list == null) {
			try {
				_episode_list = (new EpisodeAdapterImpl(_episode_url))
						.get_episode_list();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return _episode_list;
	}

}
